package com.sprucetec.live.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @auther: Wangshaobo
 * @date: 2018/11/22 18:35
 * @description:
 */
@Slf4j
@Component
public class GenerateUniqueId {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 通过key获取自增并设定过期时间
     */
    public Long generateId(String key, Date date) {
        RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        counter.expireAt(date);
        return counter.incrementAndGet();
    }



    /**
     * description 组装符合自己规则的id并设置过期时间, 23点59分59秒过期
     * @param key redis中的key值
     * @param prefix 最后编码的前缀
     * @param minLength redis生成的自增id的最小长度，如果小于这个长度前面补0
     * @return
     *  
     */
    public String generateCode(String key, String prefix, Integer minLength) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY,23);
            cal.set(Calendar.MINUTE,59);
            cal.set(Calendar.SECOND,59);
            cal.set(Calendar.MILLISECOND,999);
            Long id = this.generateId(key, cal.getTime());
            if (id != null) {
                return this.format(id, prefix, new Date(), minLength);
            }
        } catch (Exception e) {
            log.info("error-->redis生成id时出现异常");
            log.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 设定格式
     * @param id
     * @param prefix
     * @param date
     * @param minLength
     * @return
     */
    private String format(Long id, String prefix, Date date, Integer minLength) {
        StringBuffer sb = new StringBuffer();
        sb.append(prefix);
        if (date != null) {
            DateFormat df = new SimpleDateFormat("yyMMddHHmmss");
            sb.append(df.format(date));
        }
        String strId = String.valueOf(id);
        int length = strId.length();
        if (length < minLength) {
            for (int i = 0; i < minLength - length; i++) {
                sb.append("0");
            }
            sb.append(strId);
        } else {
            sb.append(strId);
        }
        return sb.toString();
    }

}
